#include "buzzer.h"
#include "music.h"
#include "stm32f4xx.h"


void buzzer_init(void)//84MHz
{
    GPIO_InitTypeDef GPIO_InitStructure;
    TIM_TimeBaseInitTypeDef TIM_TimeBaseInitStructure;
    TIM_OCInitTypeDef TIM_OCInitStructure;

    RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM4,ENABLE);
    RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOD,ENABLE);

    RCC_APB1PeriphResetCmd(RCC_APB1Periph_TIM4,ENABLE);
    RCC_APB1PeriphResetCmd(RCC_APB1Periph_TIM4,DISABLE);

    GPIO_PinAFConfig(GPIOD,GPIO_PinSource14,GPIO_AF_TIM4);

    GPIO_InitStructure.GPIO_Pin=GPIO_Pin_14;
    GPIO_InitStructure.GPIO_Mode=GPIO_Mode_AF;
    GPIO_InitStructure.GPIO_Speed=GPIO_Speed_100MHz;
    GPIO_InitStructure.GPIO_OType=GPIO_OType_PP;
    GPIO_InitStructure.GPIO_PuPd=GPIO_PuPd_DOWN;
    GPIO_Init(GPIOD,&GPIO_InitStructure);

    TIM_OCInitStructure.TIM_OCMode=TIM_OCMode_PWM1;
    TIM_OCInitStructure.TIM_OutputState=TIM_OutputState_Enable;
    TIM_OCInitStructure.TIM_OCPolarity=TIM_OCPolarity_High;
    TIM_OC3Init(TIM4,&TIM_OCInitStructure);

    TIM_OC3PreloadConfig(TIM4,TIM_OCPreload_Enable);

    TIM_ARRPreloadConfig(TIM4,ENABLE);

    TIM_TimeBaseInitStructure.TIM_Period=3000-1;
    TIM_TimeBaseInitStructure.TIM_Prescaler=84-1;
    TIM_TimeBaseInitStructure.TIM_CounterMode=TIM_CounterMode_Up;
    TIM_TimeBaseInitStructure.TIM_ClockDivision=TIM_CKD_DIV1;

    TIM_TimeBaseInit(TIM4,&TIM_TimeBaseInitStructure);

    TIM4 -> CCR3 = 1500;
}

void buzzer_on(void)
{

	static u16 i = 0;
	static u16 time = 0;
	static u16 f_arr = 0;

	f_arr = 1000000 / MyScore0[i].mName;
	TIM4 -> ARR = f_arr;
	TIM4 -> CCR3 = f_arr / 2;

	time ++;

	if(time == MyScore0[i].mTime)
	{
		i ++;
		if(MyScore0[i].mName == 0) i = 0;
		time = 0;
	}
    TIM_Cmd(TIM4,ENABLE);
}
void buzzer_off(void)
{
    TIM_Cmd(TIM4,DISABLE);
}
